import Vue from 'vue'
import VueRouter from 'vue-router'
import { Dialog } from 'vant'
import state from '@/store/'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/'),
    meta: { requiresAuth: false }
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('@/views/search/'),
    meta: { requiresAuth: false }
  },
  // 动态路由
  {
    path: '/article/:articleId',
    name: 'article',
    component: () => import('@/views/article/'),
    // 将动态路由中的参数映射到组件的 props 中
    props: true,
    meta: { requiresAuth: false }
  },
  {
    path: '/my/user-profile',
    name: 'user-profile',
    component: () => import('@/views/user-profile/'),
    meta: { requiresAuth: true }
  },
  {
    path: '/',
    component: () => import('@/views/layout/'),
    children: [
      {
        path: '', // 默认子路由，当访问首页时，默认把首页渲染到 layout 里
        name: 'home',
        component: () => import('@/views/home/'),
        meta: { requiresAuth: false }
      },
      {
        path: '/qa',
        name: 'qa',
        component: () => import('@/views/qa/'),
        meta: { requiresAuth: false }
      },
      {
        path: '/video',
        name: 'video',
        component: () => import('@/views/video/'),
        meta: { requiresAuth: true }
      },
      {
        path: '/my',
        name: 'my',
        component: () => import('@/views/my/'),
        meta: { requiresAuth: false }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// to: Route: 即将要进入的目标 路由对象
// from: Route: 当前导航正要离开的路由
// next: Function: 一定要调用该方法来 resolve 这个钩子
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !state.state.user) {
    Dialog.confirm({
      title: '请登录',
      message: '访问限制，请重新登录'
    }).then(() => {
      // 点击确认，执行这里
      router.replace({
        name: 'login',
        query: {
          redirect: router.currentRoute.fullPath
        }
      })
    }).catch(() => {
      // 点击取消，终止路由导航
      next(false)
    })
  } else {
    // 不需要登录的页面，直接放行
    next()
  }
})

export default router
